package com.reebake.ideal.message.sse;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.reebake.ideal.json.util.JsonUtil;
import com.reebake.ideal.message.core.MessageMediumTypeConstants;
import com.reebake.ideal.message.core.MessageStatusConstants;
import com.reebake.ideal.message.entity.MessageDeliveryDTO;
import com.reebake.ideal.message.entity.MessageDeliveryFeedbackDTO;
import com.reebake.ideal.message.entity.TerminalMessageDTO;
import com.reebake.ideal.message.event.MessageDeliveryEvent;
import com.reebake.ideal.message.event.MessageDeliveryFeedbackEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SseDeliveryEventListener {
    @Autowired
    private SseEmitterServer sseEmitterServer;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @EventListener
    public void handle(MessageDeliveryEvent messageDeliveryEvent) {
        MessageDeliveryDTO messageDeliveryDTO = messageDeliveryEvent.getMessageDeliveryDTO();
        List<String> supportMediumTypes = CollectionUtil.newArrayList(MessageMediumTypeConstants.APP);
        if(!supportMediumTypes.contains(messageDeliveryDTO.getMediumType())) {
            return;
        }
        String title = messageDeliveryDTO.getTitle();
        String senderName = messageDeliveryDTO.getSenderName();
        String senderAvatar = messageDeliveryDTO.getSenderAvatar();
        Boolean isBatchSend = messageDeliveryDTO.getIsBatchSend();
        Boolean enableDelivery = messageDeliveryDTO.getEnableDelivery();
        String receiverIds = messageDeliveryDTO.getReceiverIds();
        String messageHistoryId = messageDeliveryDTO.getMessageHistoryId();
        String content = messageDeliveryDTO.getContent();

        TerminalMessageDTO terminalMessageDTO = new TerminalMessageDTO();
        terminalMessageDTO.setContent(content);
        terminalMessageDTO.setReceiver(receiverIds);
        terminalMessageDTO.setTitle(title);
        terminalMessageDTO.setSender(senderName);

        sseEmitterServer.sendMessage(receiverIds, terminalMessageDTO.getId(), JsonUtil.toJsonStr(terminalMessageDTO));

        MessageDeliveryFeedbackDTO messageDeliveryFeedbackDTO = new MessageDeliveryFeedbackDTO();
        messageDeliveryFeedbackDTO.setMessageHistoryId(messageHistoryId);
        messageDeliveryFeedbackDTO.setDeliveryTime(DateUtil.date());
        messageDeliveryFeedbackDTO.setDeliveryStatus(MessageStatusConstants.DELIVERED);
        messageDeliveryFeedbackDTO.setSenderName(senderName);
        messageDeliveryFeedbackDTO.setSenderAvatar(senderAvatar);

        applicationEventPublisher.publishEvent(new MessageDeliveryFeedbackEvent(this, messageDeliveryFeedbackDTO));
    }
}
